<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection">
<title>微信登录</title>
<meta name="description" content="" />
<meta name="Keywords" content="" />
<link rel="shortcut icon" href="https://www.svenglish.cn/images/favicon.ico" type="image/x-icon">
<style>
  .login_tip{
    font-size: 0.32rem;
    position: absolute;
    left: 0;
    top: 45%;
    width: 100%;
    text-align: center;
    color: #333;
  }
</style>
</head>
<body class="login">
<div class="login_tip">微信登录中...</div>
<script>

  var getQuery = function(dataName){
		function getUrlVars(){ 
			var vars = [], hash; 
			var hashes = window.location.href.slice(window.location.href.indexOf('?')+1).split('&'); 
			for(var i = 0; i < hashes.length; i++) { 
				hash = hashes[i].split('='); 
				vars.push(hash[0]); 
				vars[hash[0]] = hash[1]; 
			} 
			return vars; 
		} 
		var params = getUrlVars(); 
		for(var i=0;i<params.length;i++){
			if(params[i]==dataName){ 
				return decodeURI(params[params[i]]);
			}
		};
		return '';
  };

  //获取code和url
  var newCode = getQuery('code'),
    url = getQuery('url');

    //检测本地是否存在过期code
  var localCode = localStorage.getItem('wxLoginCode');
  if(localCode == newCode){
    newCode = '';
  }
  
  //检测是否有code
  if(newCode==''){
    localStorage.setItem('loginUrl',url);
    location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc6d5a835c6740355&redirect_uri='+encodeURIComponent(location.href.split('?')[0])+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
  }else{

    localStorage.setItem('wxLoginCode',newCode);
    
    var xhr = new XMLHttpRequest();  // XMLHttpRequest对象用于在后台与服务器交换数据    
    xhr.open('POST', 'https://api.svenglish.cn/api/wechat/authorize');
    // xhr.setRequestHeader("Content-Type", "application/json");   
    xhr.send(newCode);
    
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { // readyState == 4说明请求已完成
        var data = JSON.parse(xhr.responseText);
        if(data.code==1){
          localStorage.setItem('wxUserInfo',JSON.stringify(data.data));
        }else{
          localStorage.setItem('wxUserInfo','');
        };
        //回调需要前往的url
        location.href = decodeURIComponent(localStorage.getItem('loginUrl'));
      }
    }
    
  };
  
  
</script>
</body>
</html>
